package com.hllxd.hism.framework.httprpc.service;

import com.alibaba.fastjson.JSON;
import com.hllxd.hism.framework.exception.BusinessException;
import com.hllxd.hism.framework.httprpc.service.dto.RequestDto;
import com.hllxd.hism.framework.httprpc.service.dto.ResponseDto;
import com.hllxd.hism.framework.httprpc.service.dto.ResponseHeader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author xiyong.lxy
 * @date 2020-10-20 9:45
 */
@Slf4j
@RestController
@RequestMapping("/cdata/framework/hrpc/")
public class RpcHttpController {

    @Autowired
    private  RestGrpcServiceBuilder restGrpcServiceBuilder;

    /**
     * 通用执行接口
     */
    @RequestMapping(value = "request.do", method = RequestMethod.POST)
    @ResponseBody
    public Object requestPost(@RequestBody String dto) {

        ResponseHeader responseHeader = new ResponseHeader();
        ResponseDto response = new ResponseDto();
        RequestDto request = JSON.parseObject(dto,RequestDto.class);

        String reqJson = request.getReqData();
        RpcReqData rpcReqData = JSON.parseObject(reqJson, RpcReqData.class);

        String mapping = rpcReqData.getPath();
        log.debug("mapping: {}, data: {}", mapping, JSON.toJSONString(rpcReqData));
        RestGrpcServiceBuilder.ClazzMethod clazzMethod = restGrpcServiceBuilder.getClazzMethod(mapping);
        if(clazzMethod==null) {
            log.warn("clazzMethod is not fund.");
            responseHeader.setCode("002");
            responseHeader.setMessage("mapping is not exist.path: " + mapping);
            response.setResult(responseHeader);
            return response;
        }
        try {
            PDRIVER_OBJECT params = new PDRIVER_OBJECT(rpcReqData.getData());
            params.userID = rpcReqData.getUserID();
            params.traceID = rpcReqData.getTraceID();
            PRESULT_OBJECT result = new PRESULT_OBJECT();
            NTSTATUS status = (NTSTATUS) clazzMethod.method.invoke(clazzMethod.clazzObject, params, result);
            responseHeader.setCode(status.code);
            responseHeader.setMessage(status.message);
            response.setData(JSON.toJSONString(result.data));
        } catch (BusinessException e) {
            log.warn("BusinessException: {}.",e.toString());
            responseHeader.setCode(e.code);
            responseHeader.setMessage(e.msg);
        } catch (Exception e) {
            log.warn("Exception: {}.",e.toString());
            responseHeader.setCode("001");
            responseHeader.setMessage("服务对象方法调用异常：" + e.toString());
            return response;
        }
        response.setResult(responseHeader);
        log.debug("response: {}.", JSON.toJSONString(response));
        return response;
    }
}
